﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing.Design;
using System.ComponentModel;
using Argos.Data.Model;
using System.Workflow.Activities;
using Argos.Windows.Forms;
using System.Windows.Forms;

namespace Argos.Design
{
	public class TargetMonitorPropertiesTypeEditor : UITypeEditor
	{

		public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
		{
			Target t = context.Instance as Target;
			if (null != t)
			{
				Dictionary<string, object> properties = new Dictionary<string, object>();

				if (null != t.MonitoringWorkflowType)
				{
					StateMachineWorkflowActivity monitor = (StateMachineWorkflowActivity)Activator.CreateInstance(t.MonitoringWorkflowType);
					Reflector.GetObjectProperties(monitor, properties, Predicates.BindableBrowsableActivityPropertyMatcher);
					if (properties.Count == 0)
					{
						throw new InvalidOperationException(string.Format("No editable properties on '{0}'.", t.MonitoringWorkflowType));
					}

					if (null != t.MonitoringWorkflowProperties)
					{
						Reflector.SetObjectProperties(monitor, t.MonitoringWorkflowProperties);
					}

					using (PropertyEditorDialog dlg = new PropertyEditorDialog(monitor))
					{
						dlg.Text = "Edit Monitor Properties";

						if (dlg.ShowDialog() == DialogResult.OK)
						{
							properties = new Dictionary<string, object>();
							Reflector.GetObjectProperties(monitor, properties, Predicates.BindableBrowsableActivityPropertyMatcher);
							return properties;
						}
					}
				}
				else
				{
					throw new InvalidOperationException("The monitor for the target has not been specified. Cannot edit monitor properties.");
				}
			}

			return value;
		}

		public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
		{
			return UITypeEditorEditStyle.Modal;
		}

	}
}
